package com.jaws.core.configuration;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.jaws.core.compatible.dao.SequenceDao;
import com.jaws.core.compatible.dao.impl.SequenceDaoImpl;
import com.jaws.core.compatible.initialize.InitializerListener;
import com.jaws.core.compatible.service.SequenceService;
import com.jaws.core.compatible.service.impl.SequenceServiceImpl;
import com.jaws.core.compatible.spring.YYNamedParameterJdbcTemplate;

@Configuration
@EnableConfigurationProperties(CompatibleProperties.class)
@ConditionalOnProperty(prefix = "jaws.compatible", name = "mode", havingValue = "true", matchIfMissing = false)
public class CompatibleConfiguration {

	@Bean
	public InitializerListener initializerListener() {
		return new InitializerListener();
	}

	@Configuration
	@ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class)
	protected class JawsSequece {

		@Bean
		@ConditionalOnBean(DataSource.class)
		public YYNamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) {
			return new YYNamedParameterJdbcTemplate(dataSource);
		}

		@Bean
		public SequenceDao sequenceDao() {
			return new SequenceDaoImpl();
		}

		@Bean
		public SequenceService sequenceService() {
			return new SequenceServiceImpl();
		}
	}

	@Configuration
	@ConditionalOnClass(SockIOPool.class)
	protected class JawsMemcached {

		@Bean(initMethod = "initialize", destroyMethod = "shutDown")
		@ConditionalOnBean(DataSource.class)
		public SockIOPool sockIOPool(CompatibleProperties compatibleProperties) {
			SockIOPool sockIOPool = SockIOPool.getInstance("neeaMemcachedPool");
			sockIOPool.setServers(compatibleProperties.getMemcache().getServer());
			sockIOPool.setInitConn(compatibleProperties.getMemcache().getInitConn());
			sockIOPool.setMaxConn(compatibleProperties.getMemcache().getMaxConn());
			sockIOPool.setMaintSleep(compatibleProperties.getMemcache().getMaintSleep());
			sockIOPool.setNagle(compatibleProperties.getMemcache().getNagle());
			sockIOPool.setSocketTO(compatibleProperties.getMemcache().getSocketTO());
			return sockIOPool;
		}

		@Bean
		public MemCachedClient memCachedClient() {
			MemCachedClient memCachedClient = new MemCachedClient("neeaMemcachedPool");
			return memCachedClient;
		}

	}

}
